<?php
	require_once('classes/All.php');
	
	$post = false;
	
	try {
		if(!isset($_REQUEST['slugtype'])) {
			$post = Post::Get($_GET['id']);
		}
		else {
			$slug_type = $_REQUEST['slugtype'];
			
			switch($slug_type) {
				case 'ymds':
					$posts = Post::GetByDay($_REQUEST['year'], $_REQUEST['month'], $_REQUEST['day'], 0, -1);
					foreach($posts as $current_post) {
						if(Utilities::URLSafe($current_post['title']) == $_REQUEST['slug']) {
							$post = $current_post;
						}
					}
					break;
				case 'cs':
					$categories = Category::GetAllCategories(0, -1);
					foreach($categories as $category) {
						if(Utilities::URLSafe($category['title']) == $_REQUEST['category']) {
							$posts = Post::GetPostsByCategory($category['categoryid']);
							foreach($posts as $current_post) {
								if(Utilities::URLSafe($current_post['title']) == $_REQUEST['slug']) {
									$post = $current_post;
								}
							}
						}
					}
					break;
			}
			
			if(!$post) {
				throw new PostNotFoundException();
			}
		}
	}
	catch(PostNotFoundException $ex) {
		HTML::ErrorPage('Post not found', 'The requested post was not found in the database.');
	}
	catch(DBConnectionException $ex) {
		HTML::ErrorPage('Database connection error', 'A database connection error occurred. Please try again in a few moments.');
	}
	catch(DBQueryException $ex) {
		HTML::ErrorPage('Database query error', 'A database query error occurred. Please try again in a few moments.');
	}
	
	HTML::Header($post['title']);
	
	Post::Display($post);
	
	Comment::Display($post['postid']);
	
	if($post['comments_enabled']) {
		Comment::DisplayForm($post['postid']);
	}
	else {
		echo '<p>Comments are not enabled for this post.</p>';
	}
	
	HTML::Footer();
?>